package com.changxianggu.crawler.cloud.test;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.changxianggu.cloud.crawler.core.WebApplication;
import com.changxianggu.cloud.crawler.core.modules.storage.entity.CxgBook;
import com.changxianggu.cloud.crawler.core.modules.storage.service.ICxgBookService;
import com.changxianggu.cloud.crawler.core.utils.HttpUtil;
import com.changxianggu.cloud.crawler.core.utils.UserAgentUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {WebApplication.class})// 指定启动类
@Slf4j
public class BeiJing {

    @Autowired
    ICxgBookService bookService;

    public static final String COOKIE = "";
    public static final String REFERER = "http://www.textbookcenter.cn/booklist/cid-7/";
    public static final String URL_PRE = "http://www.textbookcenter.cn";


    @Test
    public void initCrawler() throws Exception {
        doCrawler();
    }

    public void doCrawler() throws Exception {
        int pageNum =1;
        int totalPage = 50;
        int pageSize = 10;

        //category：本科教材7  高职教材8 中职教材9
        int category = 9;
        for (int i = pageNum; i <= totalPage; i++) {

            String url = "http://www.textbookcenter.cn/ajax/loadbooks.ashx?textbookLevel=&teachinglevel=&professionaltype=";
            Map<String, Object> parameter = MapUtil.newHashMap(3);
            parameter.put("pageIndex", i);
            parameter.put("pageSize", pageSize);
            parameter.put("category", category);
            Map<String, Object> headers = MapUtil.newHashMap(5);
            headers.put("Cookie", COOKIE);
            headers.put("User-Agent", UserAgentUtil.random());
            headers.put("Referer", REFERER);
            String result = HttpUtil.doGet(url, headers,parameter);
            while (result.contains("页面没有找到")) {
                //睡眠2秒继续访问
                Thread.sleep(2000);
                result = HttpUtil.doPost(url, headers);
            }
            if (StrUtil.isNotBlank(result)) {
                Document htmlDoc = Jsoup.parse(result);
                Elements bookContentList = htmlDoc.select("li");
                if (bookContentList != null && bookContentList.size() > 0) {
                    List<CxgBook> listBook = new ArrayList<>();
                    for (Element element : bookContentList) {
                        CxgBook bookEntity = new CxgBook();
                        CxgBook tempEntity = new CxgBook();

                        Element titleElement = element.select("h3").first();
                        if (titleElement != null) {
                            String text = titleElement.text();
                            bookEntity.setBookName(text);
                        }

                        Element priceElement = element.select(".corRed").last();
                        if (priceElement != null) {
                            String priceStr = priceElement.text().replace("￥","");
                            if (StrUtil.isNotBlank(priceStr)) {
                                try {
                                    bookEntity.setPrice(new BigDecimal(priceStr));
                                }catch (Exception e) {
                                }

                            }
                        }


                        Element imgElement = element.select(".box2ImgCon img").first();
                        if (imgElement != null) {
                            String srcStr = URL_PRE+imgElement.attr("src");
                            String cover = srcStr;
                            bookEntity.setCover(cover);
                        }


                        bookEntity.setIsSync(0);
                        bookEntity.setCreateTime(LocalDateTime.now());
                        bookEntity.setPressName("北京出版社");
                        bookEntity.setStatus(1);
                        //出版社Id不明
                        bookEntity.setPressId(192);

                        Element detailElement = element.select("a").last();
                        if (detailElement != null) {
                            String href = detailElement.attr("href");
                            String numStr = getNumbers(href);
                            tempEntity = getBookEntity(numStr,bookEntity);
                        }
                        listBook.add(tempEntity);
                    }
                    bookService.saveBatch(listBook);
                    log.info("第" + i + "页数据保存成功");
                    log.warn("--->" + i);
                }
            }
        }
    }

    public CxgBook getBookEntity(String numId,CxgBook bookEntity) throws Exception {
        String url = "http://www.textbookcenter.cn/book/"+numId+".html";
        Map<String, Object> headers = MapUtil.newHashMap(5);
        headers.put("Cookie", COOKIE);
        String result = HttpUtil.doGet(url, headers);
        while (result.contains("页面没有找到")) {
            //睡眠2秒继续访问
            Thread.sleep(2000);
            result = HttpUtil.doPost(url, headers);
        }
        if (StrUtil.isNotBlank(result)) {
            Document htmlDoc = Jsoup.parse(result);
            Element bookContent = htmlDoc.select(".detail").first();
            if (bookContent != null) {
                bookEntity.setPkId(numId);
                Element authorElement = bookContent.select(".bookTpInfor p").eq(2).first();
                if (authorElement != null) {
                    String author = authorElement.text().replace("作者：","");
                    bookEntity.setAuthor(author);
                }

                Element isbnElement = bookContent.select(".bookTpInfor p").eq(1).first();
                if (isbnElement != null) {
                    String isbn = isbnElement.text().replace("ISBN：","").replace("-","");
                    bookEntity.setBookIsbn(isbn);
                }

                Element digUriElement = bookContent.select(".bookTpBtn1 a").first();
                if (digUriElement != null) {
                    String digUriStr = digUriElement.attr("href");
                    if (StrUtil.isNotBlank(digUriStr)) {
                        bookEntity.setDigitalUri(URL_PRE+digUriStr);
                    }
                }

                //brief
                Element briefElement = bookContent.select(".bookTpBrief p").first();
                if (briefElement != null) {
                    String briefStr = briefElement.text();
                    if (StrUtil.isNotBlank(briefStr)) {
                        bookEntity.setBrief(briefStr);
                    }
                }

                //awards
                Element awardsElement = bookContent.select(".bookTpInfor p").first();
                if (awardsElement != null) {
                    String awardsStr = awardsElement.text();
                    if (StrUtil.isNotBlank(awardsStr)&&awardsStr.contains("教材级别")) {
                        bookEntity.setBrief(awardsStr.replace("教材级别：",""));
                    }
                }

                //book_version
                Element bvElement = bookContent.select(".bookCon li").eq(3).first();
                if (bvElement != null) {
                    String bvStr = bvElement.text().replace("版次：","");
                    if (StrUtil.isNotBlank(bvStr)) {
                        bookEntity.setBrief(bvStr);
                    }
                }

                //word_num
                Element wnElement = bookContent.select(".bookCon li").eq(4).first();
                if (wnElement != null) {
                    String wnStr = wnElement.text().replace("字数：","");
                    if (StrUtil.isNotBlank(wnStr)) {
                        bookEntity.setBrief(wnStr);
                    }
                }

                //catalog
                Element catalogElement = bookContent.select(".bookCon").eq(2).first();
                if (catalogElement != null) {
                    String catalogStr = catalogElement.select("li").text();
                    if (StrUtil.isNotBlank(catalogStr)) {
                        bookEntity.setCatalog(catalogStr);
                    }
                }

                //courseware_uri
                Element cuElement = bookContent.select(".classImg img").first();
                if (cuElement != null) {
                    String cuStr = cuElement.attr("src");
                    if (StrUtil.isNotBlank(cuStr)) {
                        bookEntity.setCoursewareUri(URL_PRE+cuStr);
                    }
                }
            }
        }
        return bookEntity;
    }

    /**
     * 判断一个字符串是否都为数字
     *
     * @param strNum
     * @return
     */
    public boolean isDigit(String strNum) {
        Pattern pattern = Pattern.compile("[0-9]{1,}");
        Matcher matcher = pattern.matcher((CharSequence) strNum);
        return matcher.matches();
    }

    /**
     * 截取数字
     *
     * @param content
     * @return
     */
    public String getNumbers(String content) {
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            return matcher.group(0);
        }
        return "";
    }
}
